import java.io.*;


public class Library {

	private LibraryInformation info;
	private int num;
	
	public Library(){
		this.info = LoadLibraryInformation();
		this.num = info.getNum();
	}
	
	public LibraryInformation getLibraryInformation(){
		return this.info;
	}
	
	public int getNum(){
		return this.num;
	}
	
	/*
	 * allows to manually set the info.dat data of the number of songs in the Library
	 */
	public void SetLibreryNum(int newNum){
		LibraryInformation info = new LibraryInformation(newNum);
		SaveLibraryInformation(info);
	}
	
	/*
	 * given a MusicFile, saves it to the library and updates the LibraryInformation
	 */
	public void SaveMusicFile(MusicFile mf){
		 try {
		      FileOutputStream fout = new FileOutputStream("./Library/" + this.num + ".dat");
		      ObjectOutputStream oos = new ObjectOutputStream(fout);
		      oos.writeObject(mf);
		      oos.close();
		      }
		   catch (Exception e) { e.printStackTrace(); }
		   
		  this.num +=1;
		  this.info.setNum(num);
		  SaveLibraryInformation(this.info);
	}
	
	/*
	 * given a fileNum, loads the MusicFile of the same fileNum
	 */
	public static MusicFile LoadMusicFile(int fileNum){
		MusicFile mf = new MusicFile();
		try {
			    FileInputStream fin = new FileInputStream("./Library/" + fileNum + ".dat");
			    ObjectInputStream ois = new ObjectInputStream(fin);
			    mf = (MusicFile) ois.readObject();
			    ois.close();
			    }
			   catch (Exception e) { e.printStackTrace(); }
			  
		return mf;
	}
	
	/*
	 * saves the given LibraryInformation in the Library as "info.dat"
	 */
	public static void SaveLibraryInformation(LibraryInformation info){
		
		 try {
		      FileOutputStream fout = new FileOutputStream("./Library/info.dat");
		      ObjectOutputStream oos = new ObjectOutputStream(fout);
		      oos.writeObject(info);
		      oos.close();
		      }
		   catch (Exception e) { e.printStackTrace(); }		
	}
	
	
	/*
	 * loads the LibraryInformation saved in the Library as "info.dat"
	 */
	public static LibraryInformation LoadLibraryInformation(){
		LibraryInformation info = new LibraryInformation();
		try {
			    FileInputStream fin = new FileInputStream("./Library/info.dat");
			    ObjectInputStream ois = new ObjectInputStream(fin);
			    info = (LibraryInformation) ois.readObject();
			    ois.close();
			    }
			   catch (Exception e) {
				   SaveLibraryInformation(info);
			   }
			  
		return info;
	}

}
